#pragma once
#include "const.h"
#include <jdbc/mysql_driver.h>
#include <jdbc/mysql_connection.h>
#include <jdbc/cppconn/prepared_statement.h>
#include <jdbc/cppconn/resultset.h>
#include <jdbc/cppconn/statement.h>
#include <jdbc/cppconn/exception.h>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <map>
#include "json.hpp"
using nlohmann::json;

class SqlConnection     //数据库连接
{
public:
	SqlConnection(sql::Connection* con, int64_t lasttime):_con(con), _last_oper_time(lasttime){}
	std::unique_ptr<sql::Connection> _con;	//连接对象
	int64_t _last_oper_time;	//上一次操作时间
};

class MySQLConnectionPool   //数据库连接池
{
public:
    MySQLConnectionPool(std::string url, std::string username, std::string pwd, std::string schema, int pool_size);
    ~MySQLConnectionPool();
    void checkConnection();
    std::unique_ptr<SqlConnection> getConnection();
    void returnConnection(std::unique_ptr<SqlConnection> con);
    void Close();
    void Start();
private:
    std::queue<std::unique_ptr<SqlConnection>> _pool;
    std::atomic<bool> _b_stop;
    int _pool_size;
    std::mutex _mutex;
    std::string _url;
    std::string _username;
    std::string _pwd;
    std::string _schema;
    std::thread _check_thread;
    std::condition_variable _cond;
};

class MySQLDao
{
public:
    MySQLDao();
    ~MySQLDao();
    void test();
    void getShopDatas(json& j);
    void getBannerUrls(int shop_id, json& j);
    void getShopDatasByName(json& res, const std::string& name);
private:
    std::unique_ptr<MySQLConnectionPool> _pool;
};